"""该文件用于创建模型，映射到数据库"""
from django.db import models
from django.utils.timezone import now
import requests


# Create your models here.
class ProxyIp(models.Model):
    ip = models.CharField(max_length=64)
    port = models.CharField(max_length=6)
    valid = models.BooleanField(default=True)
    create_time = models.DateTimeField(default=now)

    # 类方法,获取ip
    @classmethod
    def extract_ip(cls):
        url = "http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4"
        content = requests.get(url).text
        ip, port = content.split(":")
        print("提取一个ip:>>>{}".format(ip))
        proxy = ProxyIp(ip=ip, port=port)
        proxy.save()
        return True

    @classmethod
    def check_ip_valid(cls, ipobj):
        print("检测一个ip:----{}".format(ipobj.ip))
        url = "http://www.spbeen.com/tool/request_info/"
        proxies = {"http": "http://{}:{}".format(ipobj.ip, ipobj.port)}
        res = requests.get(url, proxies=proxies).text
        try:
            if ipobj.ip not in res:
                ipobj.valid = False
                ipobj.save()
                print("【{}】已失效".format(ipobj.ip))
            else:
                print("【{}】可用".format(ipobj.ip))
        except:
            ipobj.valid = False
            ipobj.save()
            print("【{}】已失效".format(ipobj.ip))

    def export_proxyip(self):
        pass

    # 格式化为字符串展示
    def __str__(self):
        return "【{}】{}:{}".format(self.valid, self.ip, self.port)
